package gjw.jimven.manager;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @创建者 Jimven
 * @创建时间 2017/7/11/0011  11:11
 */

/**
 * 线程管理工具类
 *
 * 通过代理模式 *****来管理线程池
 */
public class ThreadManager {
    private static ThreadPoolProxy mPoolProxy;

    /**
     * 获取线程池代理类
     */
    public static ThreadPoolProxy getThreadPoolProxy() {
        //当线程池代理类为空时，再创建
        if (mPoolProxy == null) {
            //同步检查单例
            synchronized (ThreadPoolProxy.class) {
                //创建线程池代理类
                mPoolProxy = new ThreadPoolProxy(3, 10, 1);
            }
        }
        return mPoolProxy;

    }

    /**
     * 线程池代理类，需要传入的参数 参数一:核心线程数 参数二:最大线程数 参数三:临时工的存活时间
     */
    public static class ThreadPoolProxy {
        private ThreadPoolExecutor mPoolExecutor;
        private int                corePoolSize;
        private int                maximumPoolSize;
        private long               keepAliveTime;

        public ThreadPoolProxy(int corePoolSize, int maximumPoolSize,
                               long keepAliveTime) {
            this.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.keepAliveTime = keepAliveTime;
        }

        /**
         * 在线程池代理类中，创建execute方法，传入任务Runnable参数
         *
         * @param r
         */
        public void execute(Runnable r) {
            // 当线程池为空，或者停止运行的状态
            if (mPoolExecutor == null || mPoolExecutor.isShutdown()) {
                // 创建线程池
                mPoolExecutor = new ThreadPoolExecutor(corePoolSize,
                        maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
                        new LinkedBlockingDeque<Runnable>(),
                        Executors.defaultThreadFactory());
            }
            // 不为空的状态，直接运行
            mPoolExecutor.execute(r);
        }
    }
}
